package com.woniuxy.reservation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.reservation.infra.model.TakeNum;
import com.woniuxy.reservation.infra.mapper.TakeNumMapper;
import com.woniuxy.reservation.service.TakeNumService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.reservation.service.servicedto.TakeNumServiceDto;
import com.woniuxy.reservation.service.serviceparam.InsertTakeNumServiceParam;
import com.woniuxy.reservation.service.serviceparam.SearchTakeNumByConditionServiceParam;
import com.woniuxy.table.client.TableTypeQueryClient;
import com.woniuxy.table.client.result.DinnerTableTypeClientDto;
import common.WoniuPage;
import exception.MallException;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.CommonResultCodeEnum;
import result.Result;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 排队取号表 服务实现类
 * </p>
 *
 * @author Lucas
 * @since 2023-07-21
 */
@Service
public class TakeNumServiceImpl extends ServiceImpl<TakeNumMapper, TakeNum> implements TakeNumService {

    @Autowired
    private TakeNumMapper takeNumMapper;
    @Autowired
    private TableTypeQueryClient tableTypeQueryClient;
    @Override
    @GlobalTransactional
    public void insertTakeNum(InsertTakeNumServiceParam param) {
        Result<DinnerTableTypeClientDto> tableType = tableTypeQueryClient.getTableType(param.getStoreId(), param.getTableTypeId());
        if (tableType.getData()==null) {
            throw new MallException("不存在当前餐桌类型",CommonResultCodeEnum.INVALID_PARAM);
        }
        TakeNum takeNum = BeanUtil.toBean(param, TakeNum.class);
        //查询排队时间
        QueryWrapper<TakeNum> takeNumQueryWrapper = new QueryWrapper<>();
        takeNumQueryWrapper.eq("table_type_id",param.getTableTypeId());
        takeNumQueryWrapper.eq("num_state","WAITING");
        takeNumQueryWrapper.eq("store_id",param.getStoreId());
        Integer waitTime = takeNumMapper.selectCount(takeNumQueryWrapper);
        //查询排队号
        QueryWrapper<TakeNum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id",param.getStoreId());

        LocalDate now = LocalDate.now();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String day1=now+" 00:00:00";
        String day2=now+" 24:00:00";
        Date parse1 = null;
        Date parse2 = null;
        try {
            parse1 = sdf.parse(day1);
            parse2 = sdf.parse(day2);
        } catch (ParseException e) {
            throw new MallException("日期转换错误",CommonResultCodeEnum.INVALID_PARAM);
        }
        Date date = new Date();
        queryWrapper.ge("take_num_time",parse1);
        queryWrapper.le("take_num_time",parse2);

        Integer waitNum = takeNumMapper.selectCount(queryWrapper);
        takeNum.setWaitTime((30*waitTime)+"分钟");
        takeNum.setNumState("WAITING");
        takeNum.setTakeNumTime(date);
        takeNum.setWaitNum(waitNum+1);
        save(takeNum);
    }

    @Override
    @GlobalTransactional
    public void updateTakeNumState(Integer storeId,Integer id, String numState) {
        QueryWrapper<TakeNum> takeNumQueryWrapper = new QueryWrapper<>();
        takeNumQueryWrapper.eq("store_id",storeId).eq("id",id);
        TakeNum takeNum = takeNumMapper.selectOne(takeNumQueryWrapper);
        if (takeNum==null) {
            throw new MallException("当前排队号不存在", CommonResultCodeEnum.INVALID_PARAM);
        }
        if (takeNum.getNumState().equals(numState)) {
            throw new MallException("当前排队号已为当前状态", CommonResultCodeEnum.INVALID_PARAM);
        }
        takeNum.setNumState(numState);
        takeNumMapper.updateById(takeNum);
    }

    @Override
    public WoniuPage<TakeNumServiceDto> searchTakeNumByCondition(SearchTakeNumByConditionServiceParam param) {
        QueryWrapper<TakeNum> takeNumQueryWrapper = new QueryWrapper<>();
        takeNumQueryWrapper.eq("store_id",param.getStoreId());
        if (param.getMemberId()!=null) {
            takeNumQueryWrapper.eq("member_id",param.getMemberId());
        }
        if (param.getTableTypeId()!=null) {
            takeNumQueryWrapper.eq("table_type_id",param.getTableTypeId());
        }
        if (param.getNumState()!=null&&!"".equals(param.getNumState())) {
            takeNumQueryWrapper.eq("num_state",param.getNumState());
        }
        if (param.getOrderType()!=null&&!"".equals(param.getOrderType())) {
            if (param.getOrderType().equals("升序")) {
                takeNumQueryWrapper.orderByAsc("take_num_time");
            }
            if (param.getOrderType().equals("降序")) {
                takeNumQueryWrapper.orderByDesc("take_num_time");
            }
        }
        Integer pageNum=param.getPageIndex();
        Integer pageSize=param.getPageSize();
        if (pageNum==null) {
            pageNum=1;
        }
        if (pageSize==null) {
            pageSize=5;
        }
        Page<TakeNum> page = new Page<>(pageNum,pageSize);
        takeNumMapper.selectPage(page, takeNumQueryWrapper);
        WoniuPage<TakeNumServiceDto> woniuPage = new WoniuPage<>();
        woniuPage.setTotal(page.getTotal());
        woniuPage.setPages(page.getPages());
        woniuPage.setPageIndex(page.getCurrent());
        woniuPage.setPageSize(page.getSize());
        List<TakeNumServiceDto> takeNumServiceDtos = new ArrayList<>();
        for (TakeNum takeNum : page.getRecords()) {
            TakeNumServiceDto takeNumServiceDto = BeanUtil.toBean(takeNum, TakeNumServiceDto.class);

            Result<DinnerTableTypeClientDto> result = tableTypeQueryClient.getTableType(takeNum.getStoreId(), takeNum.getTableTypeId());
            DinnerTableTypeClientDto dinnerTableTypeClientDto = result.getData();
            if (dinnerTableTypeClientDto==null) {
                throw new MallException("当前餐桌类型不存在",CommonResultCodeEnum.INVALID_PARAM);
            }
            takeNumServiceDto.setTableTypeName(result.getData().getTableTypeName());

            takeNumServiceDtos.add(takeNumServiceDto);
        }
        woniuPage.setList(takeNumServiceDtos);
        return woniuPage;
    }

    @Override
    public List<TakeNumServiceDto> searchTakeNumByTableTypeId(Integer storeId, Integer tableTypeId) {
        QueryWrapper<TakeNum> takeNumQueryWrapper = new QueryWrapper<>();
        takeNumQueryWrapper.eq("store_id",storeId).eq("table_type_id",tableTypeId);
        List<TakeNum> takeNums = takeNumMapper.selectList(takeNumQueryWrapper);
        List<TakeNumServiceDto> takeNumServiceDtos = BeanUtil.copyToList(takeNums, TakeNumServiceDto.class);
        return takeNumServiceDtos;
    }

}
